/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.module.home

import android.os.Bundle
import android.view.View
import com.orhanobut.logger.Logger
import com.tencent.map.geolocation.TencentLocationManager
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_home.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import top.stime21.framework.extension.toActivity
import top.stime21.myneighbours.Events
import top.stime21.myneighbours.R
import top.stime21.myneighbours.api.ApiManager
import top.stime21.myneighbours.base.BuzBaseFragment
import top.stime21.myneighbours.base.io_main
import top.stime21.myneighbours.module.edit.PublishActivity
import java.util.regex.Pattern


/**
 * Author: czmc  Email: zxc6355533@163.com
 * Version:	1.0  Date:2018/3/1
 */

class HomeFragment: BuzBaseFragment(){
    private val mHomeAdapter:HomeAdapter by lazy {
        HomeAdapter(fragmentManager);
    }
    override fun getLayoutId(): Int {
         return R.layout.fragment_home
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        EventBus.getDefault().register(this)
        rootView.viewPager.adapter = mHomeAdapter
        rootView.tabLayout.setupWithViewPager( rootView.viewPager)

        btn_publish.setOnClickListener({
            context!!.toActivity<PublishActivity>()
        })

        tv_city.setOnClickListener(View.OnClickListener {
            v ->
            val location = TencentLocationManager.getInstance(activity).lastKnownLocation
            if(location!=null && location.address!=null){
                setCity(location.address)
            }

            ApiManager.ins().dataApi.test("paramsssss").io_main().subscribe({
                s-> Logger.i(s)
            },{
                t-> Logger.e(t.toString())
            })

            Logger.i(ApiManager.API_URL)
        })
    }

    /**
     * 设置城市
     */
    fun setCity( address:String){
        val regex = "省(.*)市"
        val pattern = Pattern.compile(regex)
        val matcher = pattern.matcher(address)
        while (matcher.find()) {
            tv_city.text = matcher.group(1)+"市"
            break
        }
    }

    @Subscribe
    fun onRecvCityEvent(e: Events.CityNotify){
        setCity(e.address)
    }

    override fun onDestroy() {
        if(EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }


}